from threading import Thread, Lock
from multiprocessing import Process, Lock
from multiprocessing import Queue, Array, Value


#多进程锁

def save_to_pfile(index, lock):
    with lock:
        with open("ex2.log", "a", encoding="utf-8") as f:
            f.write(str(index) + "\n")

if __name__ =="__main__":
    process_array=[]
    lock = Lock()
    for i in range(10):
        p = Process(target=save_to_pfile, args=(i, lock))
        process_array.append(p)
        p.start()
        for p in process_array:
            p.join()
    print("done!")

# 多线程锁

zero = 0
lock = Lock()
def save_to_tfile():
    global zero
    for i in range(10**7):
        zero += 1
        zero -= 1

if __name__ == "__main__":
    thread_array = []
    for i in range(10):
        t = Thread(target=save_to_tfile)
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
    print("done!")
    print(zero)

# 消息队列
def save_to_queue(index, my_queue):
    my_queue.put(index)

if __name__ == "__main__":
    process_array = []
    my_queue = Queue()
    for i in range(10):
        p = Process(target=save_to_queue, args=(i, my_queue))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()

    while True:
        print(my_queue.get())

